package com.fuang.io.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * Created by Fuang on 2018-9-20.
 */
public class TimeServer {

    public void bind(int port) throws InterruptedException {
        // 创建负责Accept的线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        // 创建负责I/O读写的线程组
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap(); // 创建Netty启动类
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class) // 启动Channel
                    .option(ChannelOption.SO_BACKLOG, 1024) // 连接队列（TCP的sync_queue和accept_queue总和）大小
                    .childHandler(new ChildChannelHandler());

            // 绑定端口， 同步等待成功
            ChannelFuture f = b.bind(port).sync();

            // 等待服务端监听端口关闭
            f.channel().closeFuture().sync();
        } finally {
            // 退出，释放线程池
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

    private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            socketChannel.pipeline()
                    .addLast(new LineBasedFrameDecoder(1024)) // 按行处理TCP粘包问题
                    .addLast(new StringDecoder()) // 解码为String
                    .addLast(new ChannelHandlerTest()) // 测试ChannelHandler里的事件
                    .addLast(new TimeServerHandler());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int port = 8080;
        new TimeServer().bind(port);
    }
}
